package com.songkun.template.refrofit;


import com.songkun.template.config.manager.CacheManager;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * @描述: 网络访问工具
 * @项目名: AndroidTemplate
 * @包名: com.songkun.template.refrofit
 * @类名:
 * @作者: soongkun
 * @创建时间: 2016/4/29 13:16
 */

public class RefrofitFactory {

    private RefrofitFactory() {}

    public static <T>T create(Class<T> clazz) {

        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();

        /**
         * 设置缓存
         */
        File cacheFile = new File(CacheManager.SD_CACHE_DIR);
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
        CacheInterceptor cacheInterceptor = new CacheInterceptor();
        okHttpClient.cache(cache).addInterceptor(cacheInterceptor);
        /**
         * 公共参数
         */
        QueryParameterInterceptor queryParameterInterceptor = new QueryParameterInterceptor();
        okHttpClient.addInterceptor(queryParameterInterceptor);
        /**
         * 设置头
         */
        HeaderInterceptor headerInterceptor = new HeaderInterceptor();
        okHttpClient.addInterceptor(headerInterceptor);
        /**
         * Log信息拦截器
         */
//        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
//        loggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.BASIC);
        okHttpClient.addInterceptor(new LoggingInterceptor());


        /**
         * 设置超时和重连
         */
        okHttpClient.connectTimeout(15, TimeUnit.SECONDS);
        okHttpClient.readTimeout(20, TimeUnit.SECONDS);
        okHttpClient.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        okHttpClient.retryOnConnectionFailure(true);


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://test.ugou88.com/ugou-wx/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient.build())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(clazz);
    }
}
